const express = require('express');
const router = express.Router();
const { Order, User } = require('../database/models');
const { 
  authenticate,
  authorize,
  asyncHandler 
} = require('../middleware');

// 获取统计数据
router.get('/', 
  authenticate,
  asyncHandler(async (req, res) => {
    const currentUser = req.user;
    let query = {};

    // 根据用户角色限制查询范围
    if (currentUser.role === 'user') {
      query.userId = currentUser._id;
    } else if (currentUser.role === 'maintainer') {
      query.maintainerId = currentUser._id;
    }
    // 管理员可以看到所有数据

    // 基础统计
    const [
      totalOrders,
      pendingOrders,
      processingOrders,
      completedOrders,
      canceledOrders,
      evaluatedOrders
    ] = await Promise.all([
      Order.countDocuments(query),
      Order.countDocuments({ ...query, status: 'waiting' }),
      Order.countDocuments({ ...query, status: 'processing' }),
      Order.countDocuments({ ...query, status: 'completed' }),
      Order.countDocuments({ ...query, status: 'cancelled' }),
      Order.countDocuments({ ...query, status: 'evaluated' })
    ]);

    // 今日工单统计
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    const todayOrders = await Order.countDocuments({
      ...query,
      createdAt: {
        $gte: today,
        $lt: tomorrow
      }
    });

    // 评分统计
    const ratingResult = await Order.aggregate([
      { $match: { ...query, rating: { $exists: true, $ne: null } } },
      {
        $group: {
          _id: null,
          averageRating: { $avg: '$rating' },
          totalRatedOrders: { $sum: 1 }
        }
      }
    ]);

    const averageRating = ratingResult.length > 0 ? 
      Math.round(ratingResult[0].averageRating * 10) / 10 : 0;

    // 完成率计算
    const completionRate = totalOrders > 0 ? 
      Math.round(((completedOrders + evaluatedOrders) / totalOrders) * 100 * 10) / 10 : 0;

    // 管理员额外统计
    let adminStats = {};
    if (currentUser.role === 'admin') {
      const [
        totalUsers,
        totalMaintainers,
        activeMaintainers,
        monthlyOrdersResult,
        topMaintainersResult
      ] = await Promise.all([
        User.countDocuments({ role: 'user' }),
        User.countDocuments({ role: 'maintainer' }),
        User.countDocuments({ role: 'maintainer', isActive: true }),
        
        // 近30天工单趋势
        Order.aggregate([
          {
            $match: {
              createdAt: {
                $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
              }
            }
          },
          {
            $group: {
              _id: {
                $dateToString: {
                  format: '%Y-%m-%d',
                  date: '$createdAt'
                }
              },
              count: { $sum: 1 }
            }
          },
          { $sort: { '_id': 1 } }
        ]),
        
        // 维修员排行
        User.find({ role: 'maintainer', isActive: true })
          .select('name rating completedOrders')
          .sort({ rating: -1, completedOrders: -1 })
          .limit(5)
      ]);

      adminStats = {
        totalUsers,
        totalMaintainers,
        activeMaintainers,
        monthlyOrders: monthlyOrdersResult,
        topMaintainers: topMaintainersResult
      };
    }

    // 维修员额外统计
    let maintainerStats = {};
    if (currentUser.role === 'maintainer') {
      const maintainerOrders = await Order.find({
        maintainerId: currentUser._id,
        status: 'evaluated'
      }).select('rating serviceFee completedAt');

      const totalEarnings = maintainerOrders.reduce((sum, order) => sum + (order.serviceFee || 0), 0);
      const thisMonthStart = new Date();
      thisMonthStart.setDate(1);
      thisMonthStart.setHours(0, 0, 0, 0);

      const thisMonthOrders = maintainerOrders.filter(order => 
        order.completedAt >= thisMonthStart
      );
      const thisMonthEarnings = thisMonthOrders.reduce((sum, order) => sum + (order.serviceFee || 0), 0);

      maintainerStats = {
        totalEarnings,
        thisMonthEarnings,
        thisMonthCompletedOrders: thisMonthOrders.length,
        personalRating: currentUser.rating,
        totalCompletedOrders: currentUser.completedOrders
      };
    }

    const statistics = {
      // 基础统计
      totalOrders,
      pendingOrders,
      processingOrders,
      completedOrders,
      canceledOrders,
      evaluatedOrders,
      todayOrders,
      averageRating,
      completionRate,
      
      // 状态分布
      statusDistribution: {
        waiting: pendingOrders,
        processing: processingOrders,
        completed: completedOrders,
        cancelled: canceledOrders,
        evaluated: evaluatedOrders
      },
      
      // 角色特定统计
      ...adminStats,
      ...maintainerStats
    };

    res.status(200).json({
      success: true,
      message: '获取统计数据成功',
      code: 200,
      data: statistics
    });
  })
);

// 获取工单趋势数据
router.get('/trends', 
  authenticate,
  authorize('admin'),
  asyncHandler(async (req, res) => {
    const { period = '30' } = req.query; // 默认30天
    const days = parseInt(period);
    
    if (isNaN(days) || days < 1 || days > 365) {
      return res.status(400).json({
        success: false,
        message: '时间段参数无效，请输入1-365之间的数字',
        code: 400,
        data: null
      });
    }

    const startDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000);

    // 按日期分组统计工单
    const trendsData = await Order.aggregate([
      {
        $match: {
          createdAt: { $gte: startDate }
        }
      },
      {
        $group: {
          _id: {
            date: {
              $dateToString: {
                format: '%Y-%m-%d',
                date: '$createdAt'
              }
            },
            status: '$status'
          },
          count: { $sum: 1 }
        }
      },
      {
        $group: {
          _id: '$_id.date',
          statuses: {
            $push: {
              status: '$_id.status',
              count: '$count'
            }
          },
          total: { $sum: '$count' }
        }
      },
      { $sort: { '_id': 1 } }
    ]);

    res.status(200).json({
      success: true,
      message: '获取趋势数据成功',
      code: 200,
      data: {
        period: days,
        trends: trendsData
      }
    });
  })
);

// 获取维修员绩效统计
router.get('/maintainer-performance', 
  authenticate,
  authorize('admin'),
  asyncHandler(async (req, res) => {
    const { period = '30' } = req.query;
    const days = parseInt(period);
    const startDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000);

    const performanceData = await Order.aggregate([
      {
        $match: {
          maintainerId: { $exists: true },
          completedAt: { $gte: startDate }
        }
      },
      {
        $group: {
          _id: '$maintainerId',
          completedOrders: { $sum: 1 },
          totalEarnings: { $sum: '$serviceFee' },
          averageRating: { $avg: '$rating' },
          averageCompletionTime: {
            $avg: {
              $subtract: ['$completedAt', '$assignedAt']
            }
          }
        }
      },
      {
        $lookup: {
          from: 'users',
          localField: '_id',
          foreignField: '_id',
          as: 'maintainer'
        }
      },
      {
        $unwind: '$maintainer'
      },
      {
        $project: {
          name: '$maintainer.name',
          phone: '$maintainer.phone',
          completedOrders: 1,
          totalEarnings: { $round: ['$totalEarnings', 2] },
          averageRating: { $round: ['$averageRating', 1] },
          averageCompletionTime: {
            $round: [
              { $divide: ['$averageCompletionTime', 1000 * 60 * 60] }, // 转换为小时
              1
            ]
          }
        }
      },
      { $sort: { completedOrders: -1, averageRating: -1 } }
    ]);

    res.status(200).json({
      success: true,
      message: '获取维修员绩效统计成功',
      code: 200,
      data: {
        period: days,
        performance: performanceData
      }
    });
  })
);

// 获取收入统计
router.get('/revenue', 
  authenticate,
  authorize('admin'),
  asyncHandler(async (req, res) => {
    const { period = '30' } = req.query;
    const days = parseInt(period);
    const startDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000);

    const revenueData = await Order.aggregate([
      {
        $match: {
          completedAt: { $gte: startDate },
          serviceFee: { $exists: true, $gt: 0 }
        }
      },
      {
        $group: {
          _id: {
            $dateToString: {
              format: '%Y-%m-%d',
              date: '$completedAt'
            }
          },
          dailyRevenue: { $sum: '$serviceFee' },
          orderCount: { $sum: 1 }
        }
      },
      { $sort: { '_id': 1 } }
    ]);

    const totalRevenue = revenueData.reduce((sum, day) => sum + day.dailyRevenue, 0);
    const averageDailyRevenue = revenueData.length > 0 ? totalRevenue / revenueData.length : 0;

    res.status(200).json({
      success: true,
      message: '获取收入统计成功',
      code: 200,
      data: {
        period: days,
        totalRevenue: Math.round(totalRevenue * 100) / 100,
        averageDailyRevenue: Math.round(averageDailyRevenue * 100) / 100,
        dailyRevenue: revenueData
      }
    });
  })
);

module.exports = router;